<?php
	require_once('php/display_functions.php');
?>
<!DOCTYPE html>
<html>
	<head>
		<title>Workhorse</title>
		<style type="text/css" media="screen">@import "css/jqtouch.min.css";</style> 
		<style type="text/css" media="screen">@import "css/theme.min.css";</style>
		<meta name="viewport" content="width=device-width, user-scalable=no" />
		<meta name="apple-mobile-web- app-capable" content="yes" />
		<script src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js" type="text/javascript"></script>
		<script src="js/jqtouch.min.js" type="application/x-javascript" charset="utf-8"></script>
		<script src="js/date.js" type="text/javascript"></script>
		<script type="text/javascript">
			var jQT = $.jQTouch({
				preloadImages: [
					'css/img/back_button.png',
					'css/img/back_button_clicked.png',
					'css/img/selection.png'
				],
				icon: 'css/img/workhorse.png',
				startupScreen: 'css/img/loading.png'
			});
			var userid = 0;
		</script>
	</head>
	<body>
		<div id="login" class="current">
			<div class="toolbar">
				<h1>Login</h1>
				<a class="button flip" href="#newuser">New User</a>
			</div>
			<form name="login" action="#" method="post" onsubmit="logIn(); return false;">
				<ul class="rounded">
					<li><input type="text" id="lusername" placeholder="User Name" /></li>
					<li><input type="password" id="lpassword" placeholder="Password" /></li>
				</ul>
			</form>
		</div>
		<div id="newuser">
			<div class="toolbar">
				<a class="back flip" href="#login">Back</a>
				<h1>Create User</h1>
			</div>
			<form name="adduser" action="#" method="post" onsubmit="createUser(); return false;">
				<ul class="rounded">
					<li><input type="text" id="cusername" placeholder="User Name" /></li>
					<li><input type="password" id="cpassword" placeholder="Password" /></li>
				</ul>
			</form>
		</div>
		<div id="tasks">
			<!-- Tasks home screen -->
			<div class="tabbar">
				<a href="#tasks">Tasks</a>
				<a class="inactive swap" href="#projects">Projects</a>
			</div>
			
			<!-- Magic To Do Button -->
			<ul class="rounded">
				<li><a class="slide" id="magictodobutton" href="#magictodo">Magic To Do</a></li>
			</ul>

			<!-- Quick Add Task Form -->
			<form id="quickadd" action="#" onsubmit="quickTask(0); return false;">
			<ul class="rounded tasklist">
				<li><input type="text" name="quicktask" placeholder="Add New Task" id="quicktask" /></li>
			</ul>
			</form>
			
			<!-- Upcoming Tasks -->
			<ul id="activetasklist" class="edit rounded tasklist"> 
			</ul>
			
			<!-- Completed Tasks -->
			<ul id="completedTasks" class="rounded tasklist completed">
			</ul>
		</div>
		
		<!-- Projects Home Screen -->
		<div id="projects">
			<div class="tabbar">
				<a href="#tasks" class="inactive swap">Tasks</a>
				<a href="#projects">Projects</a>
			</div>
			<form id="addproject" action="#" onsubmit="createProject(); return false;">
			<ul class="rounded tasklist">
				<li><input type="text" name="quickproject" placeholder="Create New Project" id="quickproject" /></li>
			</ul>
			</form>
			<ul id="projectList" class="rounded">
			</ul>
		</div>
		
		<!-- Edit Task Screen -->
		<div id="edittask">
			<div class="toolbar">
				<a class="back" id="editcancel" href="#tasks">Cancel</a>
				<h1>Edit Task</h1>
				<a class="button slide" href="#tasks" data-id="0" data-complete="0" id="submit_task_edit">Save</a>
			</div>
			<form id="edittaskform" name="edittaskform" action="#" onsubmit="changeTask(); return false;">
			<ul class="edit rounded">
				<li><label for="etaskname">Name:</label><input data="0" type="text" class="float" id="etaskname" name="etaskname" placeholder="Task Title" /></li>
				<li><label class="tall">Due:</label>
					<span id="etask_nodate" data='0'>No Due Date</span>
					<span id="etask_selectdate">
						<?php printDateSelector('etask', 'dselect'); ?><br />
						<input type="button" value="None" id="etask_killdate" />
					</span>
				</li>
				<li><label for="etaskproject">Project:</label><select id="etaskproject" name="etaskproject" class="float">
					</select>
				</li>
				<li><a href="#" class="slide" id="gotoproject">Go to Project</a></li>
				<li><label for="etaskassignment">Assign:</label><select id="etaskassignment" name="etaskassignment" class="float">
				</select></li>
				<li><label for='etaskduration'>Duration:</label><input id='etaskduration' name='etaskduration' class="float" type='text' placeholder="Estimated, in min" /></li>
				<li><input type="checkbox" id="needhelp" title="I need help" /></li>
			</ul>
			<ul class="edit rounded comments">
				<li>New Comment:</li>
				<li><textarea placeholder="Create new comment" id="taskcomment"></textarea></li>
				<div id="taskcomments">
				
				</div>
			</ul>
			</form>
		</div>
		
		<!-- Project Screen -->
		<div id="project">
			<div class="toolbar">
				<a class="back slide" href="#projects">Back</a>
				<h1 id="project_title"></h1>
				<a class="button flip" id="eprojbutton" href="#">Edit</a>
			</div>
			<!-- Quick Add Task Form -->
			<form id="pquickadd" action="#" onsubmit="quickTask(current_project); return false;">
			<ul class="rounded tasklist">
				<li><input type="text" name="pquicktask" placeholder="Add New Task" id="pquicktask" /></li>
			</ul>
			</form>
			<ul class="edit rounded tasklist" id="projectActiveTasks">
			</ul>
			<ul class="edit rounded tasklist completed" id="projectCompletedTasks">
			</ul>
		</div>
		
		<!-- Edit Project Screen -->
		<div id="editproject">
			<div class="toolbar">
				<a class="back" id="eprojcancel">Cancel</a>
				<h1></h1>
				<a class="button" id="eprojsave">Save</a>
			</div>
			<form id="editproject" name="editproject" action="#" onsubmit="changeProject(); return false;">
				<ul class="edit rounded">
					<li><label for="eprojname">Name:</label><input data="0" type="text" class="float" id="eprojname" name="eprojname" placeholder="Project Title"></li>
				</ul>
				<ul class="edit rounded" id="projectmembers">
				</ul>
				<ul class="edit rounded" id="projectsharelist">
					<li>Share with:</li>
				</ul>
			</form>
		</div>
		
		<!-- Find Me Something To Do -->
		<div id='magictodo'>
			<div class='toolbar'>
				<a class='back flip' href='#'>Back</a>
				<h1>Magic Todo</h1>
				<a href='#' class='back'>Back</a>
			</div>
			<form name='magictodoform' action='#' method='post' 
					onsubmit='magictodohandler(); return false;'>
				<ul class='form'>
					<li>
						<input name='ctaskduration' id='ctaskduration' type='text' 
							placeholder='Enter desired task length in minutes' />
					</li>
				</ul>
			</form>
			<ul id='magictodolist' class='rounded'>
			</ul>
		</div>

		<script type="text/javascript">
			var current_project = 0;
			var current_task = 0;
			/*$('document').ready(function()	{
				userid = 2;
				initialize();
			});*/
			
			/** Function: changeProject
			  * -----------------------
			  * Writes any changes made on the editproject pane to the
			  * database and redirects the user to the project page.
			  */
			function changeProject()	{
				var postdata = {
					user: userid,
					proj: current_project,
					name: document.getElementById('eprojname').value
				}
				postdata.invitees = '';
				$('.invitee', '#editproject').each(function()	{
					if(this.checked)
						postdata.invitees += $(this).attr('id').substring(6) + ',';
				});
				$('h2', '#editproject').html(postdata.name);
				$('#eprojname').val(postdata.name);
				document.getElementById('project_title').innerHTML = postdata.name;
				postdata.invitees = postdata.invitees.substring(0, postdata.invitees.length);
				jQuery.post('php/updateproject.php', postdata, function(data)	{
					jQuery.post('php/writeprojectlist.php', {user: userid}, function(data)	{
						document.getElementById('projectList').innerHTML = data;
						resetProjectList();
						jQT.goTo('#project', 'flip');
					});
				});
			}
			
			/** Function: createUser
			  * --------------------
			  * Creates a new user and automatically logs in with the
			  * new user name.
			  */
			function createUser()	{
				var postdata = {
					username: document.getElementById('cusername').value,
					password: document.getElementById('cpassword').value
				};
				jQuery.post('php/adduser.php', postdata, function(data) {
					if(!data)	{
						alert("Error creating user");
						return false;
					}	else	{
						userid = data;
						initialize();
					}
				});
			}
			
			/** Funtion: updateProjectLists
			  * ---------------------------
			  * Reloads the lists of the user's projects from the databases and
			  * updates the projects pane and the project selector on the task
			  * edit pane accordingly.
			  */
			function updateProjectLists()	{
				jQuery.post('php/writeprojectlist.php', {user: userid}, function(data)	{
					document.getElementById('projectList').innerHTML = data;
					resetProjectList();
				});
				jQuery.post('php/writeprojectselect.php', {user: userid}, function(data)	{
					document.getElementById('etaskproject').innerHTML = data;
				});
			}
			
			/** Function: checkInvitations
			  * --------------------------
			  * Checks for any new invitations for the given user. For each new
			  * invitation, prompts the user to accept or reject and queries the
			  * database accordingly.
			  */
			function checkInvitations()	{
				jQuery.post('php/checkinvitations.php', {user:userid}, function(data)	{
					for(var i = 0; i < data.length; i++)	{
						var accept = 0;
						if(confirm(data[i].inviter + " has invited you to join the project \"" + data[i].projectname + ".\""))
							accept = 1;
						jQuery.post('php/processinvite.php', {proj: data[i].projectid, user:userid, accepted:accept}, updateProjectLists);
					}
				}, 'json');
			}
			
			/** Function: loadTaskLists
			  * -----------------------
			  * Loads the user's list of tasks from the database and
			  * updates the active and completed lists accordingly.
			  */
			function loadTaskLists()	{
				jQuery.post('php/gettasklist.php',{user: userid}, function(data)	{
					document.getElementById('activetasklist').innerHTML = data;
					resetListFunctionality();
				});
				jQuery.post('php/gettasklist.php', {user: userid, completed:1, project:0, checked:true, sort:'DESC'}, function(data)	{
					document.getElementById('completedTasks').innerHTML = data;
					resetListFunctionality();
				});
			}
			
			/** Function: initialize
			  * --------------------
			  * Loads the home screen and project list.
			  */
			function initialize()	{
				jQT.goTo('#tasks', 'slide');
				$('#magictodobutton').click(function()	{
					document.getElementById('ctaskduration').value = '';
					document.getElementById('magictodolist').innerHTML ='';
				});
				$('#eprojsave').click(changeProject);
				$('#submit_task_edit').click(function()	{
					changeTask();
				});
				$('#etask_killdate').click(function()	{
					$('#etask_nodate').css('display','block').attr('data',0);
					$('#etask_selectdate').css('display','none')
				});
				checkInvitations();
				loadTaskLists();
				updateProjectLists();
			}
			
			/** Function: logIn
			  * ---------------
			  * Checks a username and password combination. Logs in
			  * if the combination is valid, provides an alert
			  * otherwise.
			  */
			function logIn()	{
				var postdata = {
					username: document.getElementById('lusername').value,
					password: document.getElementById('lpassword').value
				}
				jQuery.post('php/login.php', postdata, function(data)	{
					if(!data)	{
						alert("Invalid user name/password combination.");
						return false;
					}	else	{
						userid = data;
						initialize();
					}
				});
			}
			
			/** Function: resetProjectTaskList
			  * ------------------------------
			  * Resets the javascript functionality for the project
			  * task lists.
			  */
			function resetProjectTaskList()	{
				$('li.task', '#project').unbind().click(function()	{
					editTask($(this).children('.taskbox').attr('id').substring(7));
					$('#editcancel').attr('href', '#project');
				});
				$('.taskbox').unbind().click(function()	{
					toggleComplete(current_project, this);
				});
			}
			
			/** Function: resetProjectList
			  * --------------------------
			  * Resets the click functionality of items in the list
			  * of projects.
			  */
			function resetProjectList()	{
				$('a.projectLink').unbind().click(function()	{
					current_project = $(this).attr('data-id');
					$('#eprojbutton').unbind().click(function()	{
						jQuery.post('php/getProjectData.php', {id:current_project}, function(data)	{
							$('h1', '#editproject').html(data.project_name);
							document.getElementById('projectsharelist').innerHTML = "<li>Share with:</li>" + data.contacts;
							document.getElementById('eprojname').value = data.project_name;
							var mems = "<li>Project Members:</li><li>";
							for(var i = 0; i < (data.members).length; i++)
								mems += (data.members)[i] + ", ";
							mems = mems.substring(0, mems.length - 2) + "</li>"
							document.getElementById('projectmembers').innerHTML = mems;
							jQT.goTo('#editproject', 'flip');
						}, 'json');
						return false;
					});
					jQuery.post('php/getProjectData.php', {id:current_project}, function(data)	{
						document.getElementById('project_title').innerHTML = data.project_name;
						jQT.goTo('#project', 'slide');
					}, 'json');
					jQuery.post('php/getprojecttasks.php', {user:userid, proj:current_project, completed:0}, function(data)	{
						document.getElementById('projectActiveTasks').innerHTML = data;
						resetProjectTaskList();
					});
					jQuery.post('php/getprojecttasks.php', {user:userid, proj:current_project, completed:1}, function(data)	{
						document.getElementById('projectCompletedTasks').innerHTML = data;
						resetProjectTaskList();
					});
					return false;
				});
			};
			$('#etask_nodate').click(function()	{
				$(this).css('display','none').attr('data',1);
				$('#etask_selectdate').css('display','inline');
			});
			
			/** Function: createProject
			  * -----------------------
			  * Creates a new project.
			  */
			function createProject()	{
				var name = $('#quickproject').val();
				$('#quickproject').val('').blur();
				var postdata = {
					name: name,
					user: userid
				}
				jQuery.post('php/makeproject.php', postdata, function(data)	{
					document.getElementById('projectList').innerHTML = data;
					jQuery.post('php/getprojectlist.php', {user: userid}, function(data)	{
						document.getElementById('etaskproject').innerHTML = data;
					});
					resetProjectList();
				});
			}
			
			/** Function: changeTask
			  * --------------------
			  * Calls to the database to update the task and sends the user
			  * back one page.
			  */
			function changeTask()	{
				var name = $('#etaskname').val();
				if(name.length < 1)	{
					alert("You must enter a task name.");
					return false;
				}
				var postdata = {
					id: $('#submit_task_edit').attr('data-id'),
					name: name,
					month: document.getElementById('etask_month').value,
					date: document.getElementById('etask_date').value,
					year: document.getElementById('etask_year').value,
					hour: document.getElementById('etask_hour').value,
					minute: document.getElementById('etask_minute').value,
					duedate: $('#etask_nodate').attr('data'),
					proj: $('#etaskproject').val(),
					user: userid,
					completed: $('#submit_task_edit').attr('data-complete'),
					comment: document.getElementById('taskcomment').value,
					assign: document.getElementById('etaskassignment').value,
					duration: document.getElementById('etaskduration').value,
					help: (document.getElementById('needhelp').checked ? 1 : 0)
				};
		
				jQuery.post('php/updatetask.php', postdata, function(data)	{
					data = data.split("\n\t\n");
					var html = data[1];
					var com = data[0];
					if(com == 1)
						document.getElementById('completedTasks').innerHTML = html;
					else
						document.getElementById('activetasklist').innerHTML = html;
					resetListFunctionality();
					$('#projectActiveTasks').load('php/getprojecttasks', {user:userid, completed:0, proj:current_project}, function()	{
						resetProjectTaskList();
					});
					document.getElementById('taskcomment').value = '';
					jQT.goTo($('#editcancel').attr('href'), 'slide');
				});
			}
			
			/** Function: resetListFunctionality
			  * --------------------------------
				* Must be called whenever the main task lists are changed.
				* Re-enables click functionality on task list items. Will
				* eventually update all task lists.
				*/
			function resetListFunctionality()	{
				$('li.task', '#tasks').unbind().click(function()	{
					editTask($(this).children('.taskbox').attr('id').substring(7));
					$('#editcancel').attr('href', '#tasks');
				});
				$('.taskbox').unbind().click(function()	{
					toggleComplete(0, this);
				});
			}
			
			/** Function: editTask
			  * ------------------
			  * Sends the user to the edit task page and loads the relevant
			  * task information into the correct fields.
			  * @param taskID: the unique ID for the task
			  */
			function editTask(taskID)	{
				jQuery.post('php/gettaskdata.php', {id: taskID}, function(data)	{
					document.getElementById('etaskassignment').innerHTML = data.members;
					document.getElementById('etaskassignment').value = data.assigned_to;
					document.getElementById('etaskduration').value = (data.time_to_complete_in_minutes == 0 ? '':data.time_to_complete_in_minutes) ;
					document.getElementById('etaskproject').value = data.project_id;
					$('#etaskname').attr('value',data.task_name);
					if(!data.due_time_from)	{
						$('#etask_nodate').css('display','block').attr('data',0);
						$('#etask_selectdate').css('display', 'none');
					}	else	{
						$('#etask_nodate').css('display','none').attr('data',1);
						$('#etask_selectdate').css('display', 'inline');
						var time = (data.due_time_from).split(',');
						document.getElementById("etask_month").value = time[0];
						document.getElementById("etask_date").value = time[1];
						document.getElementById("etask_year").value = time[2];
						document.getElementById("etask_hour").value = time[3];
						document.getElementById("etask_minute").value = (time[4] - (time[4] % 5));
						document.getElementById("etaskproject").value = parseInt(data.project_id);
					}
					current_project = data.project_id;
					$('#gotoproject').unbind().click(function()	{
						jQuery.post('php/getProjectData.php', {id:current_project}, function(data)	{
							$('h1', '#editproject').html(data.project_name);
							document.getElementById('projectsharelist').innerHTML = "<li>Share with:</li>" + data.contacts;
							document.getElementById('eprojname').value = data.project_name;
							var mems = "<li>Project Members:</li><li>";
							for(var i = 0; i < (data.members).length; i++)
								mems += (data.members)[i] + ", ";
							mems = mems.substring(0, mems.length - 2) + "</li>"
							document.getElementById('projectmembers').innerHTML = mems;
							jQT.goTo('#editproject', 'slide');
						}, 'json');
						return false;
					});
					document.getElementById('taskcomments').innerHTML = data.comments;
					$('#submit_task_edit').attr('data-complete', (data.completed));
					if(data.help_required == 1)
						document.getElementById('needhelp').checked = true;
					else
						document.getElementById('needhelp').checked = false;
					jQT.goTo('#edittask', 'slide');
				}, 'json');
				$('#submit_task_edit').attr('data-id', taskID);
			}
			
			/** Function: toggleComplete
			  * ------------------------
			  * Toggles the completed status of a task.
			  */
			function toggleComplete(project, obj)	{
				var id = $(obj).attr('id').substring(7);
				var li = $(obj).parent();
				$(li).remove();
				if($(obj).attr('id').indexOf('ptsk') > -1)
					$('#taskbox' + id).parent().remove();
				var completed = 1;
				if(!obj.checked)	completed = 0;
				jQuery.post('php/completetask.php', {id: id, complete: completed, user:userid}, function(data)	{
					var com = data.split("\n\t\t\n")[0];
					var html = data.split("\n\t\t\n")[1];
					if(com == 1)	{
						document.getElementById('completedTasks').innerHTML = html;
						jQuery.post('php/getprojecttasks', {user:userid, completed:1, proj:project}, function(data)	{
							document.getElementById('projectCompletedTasks').innerHTML = data;
							resetProjectTaskList();
						});
					}	else	{
						document.getElementById('activetasklist').innerHTML = html;
						jQuery.post('php/getprojecttasks', {user:userid, completed:0, proj:project}, function(data)	{
							document.getElementById('projectActiveTasks').innerHTML = data
							resetProjectTaskList();
						});
					}
					resetListFunctionality();
				});
				return false;
			}
			
			/** Function: quickTask(proj)
			  * -------------------------
			  *	Creates a new task by parsing a single line of input into
			  * a task title and due date.
			  *
			  * @param proj: optional parameter specifying the id of the project
			  * 	to which the task should be added
			  */
			function quickTask(proj)	{
				var english;
				//Grab user input from the proper source
				if(!proj)	{
					proj = 0;
					english = document.getElementById('quicktask').value;
				}	else	{
					english = document.getElementById('pquicktask').value;
				}

				//Process due date, if any
				if(english.length < 1)	return false;
				var title = english;
				var due = new Date();
				due.setTime(2012345000000 + due.getTimezoneOffset());
				var setdate = false;
				if(english.indexOf(' due ') > -1)	setdate = ' due ';
				if(english.indexOf(' by ') > -1)	setdate = ' by ';
				if(setdate)	{
					english = english.split(setdate);
					title = english[0].trim();
					due = Date.parse(english[1].trim());
					if(due == null)	{
						alert("Invalid due date.");
						return false;
					}
					if(due.getHours() == 0)
						due.setHours(23,59,59);
					due.setTime(due.getTime() + (due.getTimezoneOffset()*60*1000));
				}
				
				var postdata = {
					name: title,
					date: due,
					user: userid,
					project: proj
				}
				
				//Make the database call to add the task
				jQuery.post('php/addtask.php', postdata, function(data)	{
					document.getElementById('activetasklist').innerHTML = data;
					resetListFunctionality();
					if(!proj)	{
						$('#quicktask').val('').blur();
					}	else	{
						$('#pquicktask').val('').blur();
						$('#projectActiveTasks').load('php/getprojecttasks', {user:userid, completed:0, proj:proj}, function()	{
							resetProjectTaskList();
						});
					}
				});
			}
			
			function magictodohandler(){
				var postdata = {
					taskduration: document.getElementById('ctaskduration').value,
					user: userid
				};
				$.post('php/magictodo.php', postdata, function(data) {
					document.getElementById('magictodolist').innerHTML=data;
					$('#ctaskduration').blur();
				});
				return false;
			}
			
			String.prototype.trim = function() {
				return this.replace(/^\s+|\s+$/g,"");
			};
		</script>
	</body>
</html>
